package tools.phylip;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

public class Phylipparser {

	private BufferedReader in;
	private ArrayList<PhylipSeq> current,next;
	private boolean more;
	private String s;
	
	public Phylipparser(String inFile)throws Exception{
		in=new BufferedReader(new FileReader(inFile));
		more=false;
		readNext();
	}
	public boolean hasMore(){
		return more;
	}
	public ArrayList<PhylipSeq> nextSubsection()throws Exception{
		if(hasMore()){
		current=new ArrayList<PhylipSeq>();
		current.addAll(next);
		readNext();
		}else{
			throw new Exception("No more too read...");
		}
		return current;
	}
	
	private void readNext()throws Exception{
		s=in.readLine();
		if(s==null){
			more=false;
		}else{
			try{
				String[] l=s.split(" +");
//				System.out.println(l[1]+","+l[2]);
				int antal=Integer.parseInt(l[1]);
				int length=Integer.parseInt(l[2]);
				next=new ArrayList<PhylipSeq>();
				//read all sequence names and the beginning of their sequences
				for(int i=0;i<antal;i++){
					s=in.readLine();
					PhylipSeq tmp=new PhylipSeq(s.substring(0, 11).replaceAll(" +$", ""),s.substring(11).replaceAll(" +", ""));
					next.add(tmp);
				}
				for(int read=60;read<length;read+=60){
					s=in.readLine();
					if(s.length()>0){
						System.err.println("Expected empty line...");
						throw new Exception();
					}
					for(int i=0;i<antal;i++){
						s=in.readLine();
						if(!s.startsWith("           ")){
							System.err.println("Incorrect beginning of line...");
							throw new Exception();
						}
						next.get(i).append(s.replaceAll(" +", ""));
//						System.out.println(next.get(i).toFastaSeq());
					}
				}
				s=in.readLine();
				more=true;
			}catch(Exception e){
				System.err.println("Corrupt line: "+s);
				e.printStackTrace(System.err);
				more=false;
			}
		}
	}
	
	public static void main(String[] args)throws Exception{
		Phylipparser pp=new Phylipparser(args[0]);
	}
}
